package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Resource
    StringRedisTemplate  stringRedisTemplate;



    @Override
    public Result sendCode(String phone) {

        //校验手机
        if (RegexUtils.isPhoneInvalid(phone)) {
            //手机格式错误
            return  Result.fail("手机格式错误");
        }

        //发送存储验证码
        String code = RandomUtil.randomNumbers(6);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone, code,LOGIN_USER_TTL, TimeUnit.SECONDS);

        log.debug("发送验证码成功，验证码：{}", code);

        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm) {

        //校验手机
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            //手机格式错误
          return  Result.fail("手机格式错误");
        }

        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+loginForm.getPhone());

        if (cacheCode == null || !cacheCode.equals(loginForm.getCode())) {
            //验证码错误
            return  Result.fail("验证码错误");
        }

        LambdaQueryWrapper<User> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, loginForm.getPhone());
        User user = this.getOne(queryWrapper);
        if (user == null) {
            user = createUserWithPhone(loginForm.getPhone());
        }
        UserDTO  dto= new UserDTO();
        BeanUtil.copyProperties(user,dto);

        Map<String, Object> userMap = BeanUtil.beanToMap(dto,new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((key, value) -> value.toString()));

        String token = UUID.randomUUID().toString(true);

        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token, userMap);

        stringRedisTemplate.opsForHash().getOperations().expire(LOGIN_USER_KEY+token, LOGIN_USER_TTL, TimeUnit.MINUTES);


        return  Result.ok(token);
    }

    @Override
    public Result me(String token) {


        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY+token);

        if(userMap.isEmpty()){
            return  Result.fail("用户不存在");
        }
        UserDTO userDto = new UserDTO();
        BeanUtil.fillBeanWithMap(userMap, userDto, false);

        UserHolder.saveUser(userDto);

        return Result.ok(userDto);
    }

    @Override
    public  void logout(String token) {

        stringRedisTemplate.opsForHash().getOperations().delete(LOGIN_USER_KEY+token);
        UserHolder.removeUser();


    }


    private User createUserWithPhone(String phone) {
        // 1.创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        // 2.保存用户
        save(user);
        return user;
    }
}
